package com.hoshino.momochi.config;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.hoshino.momochi.model.domain.Blog;
import com.hoshino.momochi.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Date;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Component
public class CacheTask {


    @Autowired
    private RedisService redisService;

    @Autowired
    private BlogLikeService blogLikeService;
    @Autowired
    private BlogService blogService;
    @Autowired
    private BlogTagService blogTagService;
    @Autowired
    private CollectionBlogService collectionBlogService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private FocusService focusService;
    @Autowired
    private HistoryReadService historyReadService;
    @Autowired
    private SubscribeService subscribeService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserDetailsService userDetailsService;

//    @Scheduled(cron = "0 0 1 * * ?")
    public void cache() {
        // 用户注销过后 清除 用户 的信息 待补充

        // 定期清除
        blogLikeService.delIsDeleteAsTrue();
        blogService.delIsDeleteAsTrue();
        blogTagService.delIsDeleteAsTrue();
        collectionBlogService.delIsDeleteAsTrue();
        commentService.delIsDeleteAsTrue();
        focusService.delIsDeleteAsTrue();
        historyReadService.delIsDeleteAsTrue();
        subscribeService.delIsDeleteAsTrue();
//        userService.delIsDeleteAsTrue();
        userDetailsService.delIsDeleteAsTrue();
    }

    @Value("${server.resource}")
    private String resourcePath;

    @Value("${spring.datasource.username}")
    private String userName;

    @Value("${spring.datasource.password}")
    private String passWord;

    @Value("${database-name}")
    private String dbName;

    /**
     * 定时备份数据库信息
     */
    @Scheduled(cron = "0 0 5 * * ?")
    public void backUpDataBase() {
        System.out.println("======执行定时器:定时备份数据库=======");
        String backUpPath = resourcePath + "/sql/" + Date.valueOf(LocalDate.now());
        File backUpFile = new File(backUpPath);
        if (!backUpFile.exists()) {
            backUpFile.mkdirs();
        }
        File dataFile = new File(backUpPath + "/database" + System.currentTimeMillis() + ".sql");
        //拼接cmd命令
        StringBuffer sb = new StringBuffer();
        sb.append("mysqldump");
        sb.append(" -u" + userName);
        sb.append(" -p" + passWord);
        sb.append(" " + dbName + " > ");
        sb.append(dataFile);
        System.out.println("======数据库备份cmd命令为：" + sb.toString() + "=======");
        try {
            Process exec = Runtime.getRuntime().exec("cmd /c" + sb.toString());
            if (exec.waitFor() == 0) {
                System.out.println("======数据库备份成功，路径为：" + dataFile + "=======");
            }
        } catch (Exception e) {
            System.out.println("======数据库备份失败，异常为：" + e.getMessage() + "=======");
        }
    }

    /**
     * 定时删除数据库备份文件，只保留最近一个星期
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void deleteBackUpDataBase() {
        System.out.println("======执行定时器:定时删除备份数据库文件=======");
        String backUpPath = resourcePath + "/sql";
        File backUpFile = new File(backUpPath);
        if (backUpFile.exists()) {
            File[] files = backUpFile.listFiles();
            for (File file : files) { // file -> sql 文件
                if (file.isDirectory()) {
                    Date date1 = Date.valueOf(file.getName()); // 文件时间
                    Date date2 = Date.valueOf(LocalDate.now()); // 现在时间
                    long betweenDay = DateUtil.between(date1, date2, DateUnit.DAY); // 相差时间
                    if (betweenDay > 7) {
                        File[] subFiles = file.listFiles();
                        for (File subFile : subFiles) {
                            subFile.delete();
                        }
                        file.delete();
                    }
                }
//                System.out.println(file.getName());
            }
        }
    }
}
